package com.angel.crowd.mvc.controller;

import com.angel.crowd.constant.CrowdConstant;
import com.angel.crowd.entity.Admin;
import com.angel.crowd.service.AdminService;
import com.angel.crowd.util.CrowdUtil;
import com.angel.crowd.util.ResultEntity;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author yuzhen
 * @create 2020-05-03 21:28
 */
@Controller
public class AdminController {

    @Autowired
    private AdminService adminService;


    @RequestMapping(value = "/admin/do/logout.html")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/admin/to/login/page.html";
    }

    /**
     * 用springSecurity代替登录验证
     * @param loginAcct
     * @param userPswd
     * @param session
     * @return
     */
    @RequestMapping(value = "/admin/do/login.html")
    public String doLogin(
            @RequestParam("loginAcct") String loginAcct,
            @RequestParam("userPswd") String userPswd,
            HttpSession session){

        // 调用Service方法执行登录检查
        // 这个方法如果能够返回admin对象说明登录成功，如果账号、密码不正确则会抛出异常
        Admin admin = adminService.getAdminByLoginAcct(loginAcct, userPswd);
        // 将登录成功返回的admin对象存入Session域
        session.setAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN, admin);
        return "redirect:/admin/to/main/page.html";
        //return "admin-main";
    }

    @RequestMapping("/admin/get/page.html")
    public String getAdminPage(
            // 注意：页面上有可能不提供关键词，要进行适配
            // 在@RequestParam注解中设置defaultValue属性为空字符串表示浏览器不提 供关键词时，keyword 变量赋值为空字符串
            @RequestParam(value = "keyword",defaultValue = "") String keyword,
            // 浏览器未提供 pageNum 时，默认前往第一页
            @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize,
            ModelMap modelMap
    ){
        PageInfo<Admin> pageInfo = adminService.getPageInfo(keyword, pageNum, pageSize);
        modelMap.addAttribute(CrowdConstant.ATTR_NAME_PAGE_INFO,pageInfo);
        return "admin-page";
    }

    @RequestMapping(value = "/admin/remove/{adminId}/{pageNum}/{keyword}.html")
    public String remove(
            @PathVariable("adminId") Integer adminId,
            @PathVariable("pageNum") Integer pageNum,
            @PathVariable("keyword") String keyword
    ){
        // 执行删除
        adminService.remove(adminId);

        // 页面跳转：回到分页页面
        // 尝试方案1：直接转发到admin-page.jsp会无法显示分页数据
        // return "admin-page";
        // 尝试方案2：转发到/admin/get/page.html地址，一旦刷新页面会重复执行删除浪费性能
        // return "forward:/admin/get/page.html";
        // 尝试方案3：重定向到/admin/get/page.html地址
        // 同时为了保持原本所在的页面和查询关键词再附加pageNum和keyword两个请求参数
        return "redirect:/admin/get/page.html?pageNum="+pageNum+"&keyword="+keyword;
    }

    @PreAuthorize("hasAuthority('role:save')")
    @RequestMapping(value = "admin/save.html")
    public String saveAdmin(Admin admin){
        adminService.saveAdmin(admin);
        return "redirect:/admin/get/page.html?pageNum=" + Integer.MAX_VALUE;
    }

    @RequestMapping(value = "/admin/to/edit/page.html")
    public String toEditPage(@RequestParam("adminId") Integer adminId,ModelMap modelMap){
        // 1.根据adminId查询Admin对象
        Admin admin = adminService.getAdminById(adminId);
        modelMap.addAttribute("admin",admin);
        return "admin-edit";
    }

    @RequestMapping(value = "/admin/update.html")
    public String update(Admin admin,
                         @RequestParam("pageNum") Integer pageNum,
                         @RequestParam("keyword") String keyword){
        adminService.update(admin);
        return "redirect:/admin/get/page.html?pageNum=" + pageNum + "&keyword=" + keyword;
    }


    @PreFilter(value="filterObject%2==0")
    @ResponseBody
    @RequestMapping("/admin/test/pre/filter")
    public ResultEntity<List<Integer>> saveList(@RequestBody List<Integer> valueList) {
        return ResultEntity.successWithData(valueList);
        /**
         * @PreFilter：在方法执行前对传入的参数进行过滤。只能对集合类型的数据进行过滤。
         * @PostFilter：在方法执行后对方法返回值进行过滤。只能对集合类型的数据进行过滤。
         * 1.在postman 用post访问http://localhost:8080/angelcrowdfunding02_admin_webui/admin/test/pre/filter.json
         * 2.设置Headers:
         *      key:Content-Type   value:application/json
         *      key:Cookie         value:JSESSIONID=3182E9E2AAF43A3658563699AD6A86FF  //value值用浏览器登录后在存储下的cookie 复制值
         * 3.设置Body下的raw的值:
         *      [1,2,3,4,5,6,7,8,9,10]
         * 4.点访问
         * 5.获得偶数数据:
         *      {"result": "SUCCESS","message": null,"data":
         *        [2,
         *         4,
         *         6,
         *         8,
         *         10]
         *       }
         */
    }

}
